# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python

import os
from fnmatch import fnmatch

from cerbero.build.filesprovider import FilesProvider
from cerbero.utils import shell
from cerbero.tools.libtool import LibtoolLibrary


class Recipe(recipe.Recipe):
    name = 'nettle'
    version = '3.4'
    stype = SourceType.TARBALL
    url = 'gnu://.tar.gz'
    tarball_checksum = 'ae7a42df026550b85daca8389b6a60ba6313b0567f374392e54918588a411e94'
    licenses = [License.LGPLv3Plus, License.GPLv2Plus, License.GPLv3Plus]
    configure_options = '--enable-shared --enable-public-key'
    deps = ['gmp']
    patches = [name + '/0001-ios-fix-build-using-.word-for-assembly-constants.patch']
    allow_parallel_build = False

    files_bins = ['nettle-hash', 'nettle-lfib-stream', 'nettle-pbkdf2']
    files_libs = ['libnettle', 'libhogweed']
    files_devel = ['include/nettle', 'lib/pkgconfig/nettle.pc', 'lib/pkgconfig/hogweed.pc']

    async def configure(self):
        shell.replace(os.path.join(self.build_dir, 'Makefile.in'),
            {'SUBDIRS = tools testsuite examples':
             'SUBDIRS = tools'})
        await super(recipe.Recipe, self).configure()

    def post_install(self):
        # Create libtool libraries (.la)
        libtool_la = LibtoolLibrary('nettle', 6, 2, None, self.config.libdir,
                self.config.target_platform)
        libtool_la.save()
        deps = ['nettle', 'gmp']
        if self.config.target_platform != Platform.LINUX:
            deps += ['intl']
        if self.config.target_platform != Platform.WINDOWS:
            deps += ['-lc']

        libtool_la = LibtoolLibrary('hogweed', 4, 2, None, self.config.libdir,
                self.config.target_platform, deps)
        libtool_la.save()

        if self.config.target_platform == Platform.LINUX:
            # Fix the libs permissions to 0755 to make the rpm packaging happy.
            # Setting for all linux distros as this may affect suse as well.
            # It will not affect debian packaging as it will run dh_fixperms
            # which does the right thing for debian.
            libs = self.files_list_by_category(FilesProvider.LIBS_CAT)
            for lib in libs:
                f = os.path.join(self.config.prefix, lib)
                if os.path.isfile(f) and not os.path.islink(f) and \
                   fnmatch(f, '*.so.*'):
                    os.chmod(f, 0o755)
        super().post_install()
